import http = require('http')
import url = require('url')

import { loadContent } from './compress';

const APP_CONFIG = require('../config/app.json')

//页面访问次数
let view_counter = 0
//创建緩存
let cache = {}

//导出入口函数 startHttp
//handle在这里是一个函数
export function startHttp (route, handle) {
	//第一次调用此函数才会触发	
	console.log('Server has started.')
	//监听8888端口
	http.createServer(onRequest).listen(APP_CONFIG.server_port)
	//监听不同端口
	http.createServer(onRequest).listen(APP_CONFIG.web_port)

	function onRequest (request: http.IncomingMessage, response: http.ServerResponse): http.RequestListener {
		//获取端口
		const port = +request.headers.host.split(':')[1]
		//获取路由
		const pathname = url.parse(request.url).pathname

		const params = url.parse(request.url, true).query

		//过滤浏览器对/favicon.ico的请求,否则部分浏览器会向服务端请求两次
		if (pathname === '/favicon.ico') {
			return
		}

		console.log(`Request port:${port}.`)
		console.log(`Request for ${pathname} received.`)


		//处理不同端口的请求
		switch (port) {
			case APP_CONFIG.server_port:
				route(handle, pathname, response, params)
				break
			case APP_CONFIG.web_port:
				loadContent(request, response)
				break
			default:
				break
		}
		if (port != APP_CONFIG.web_port) {
			//如果页面已经有response不再返回
			console.log(response.statusCode)
			if (response.statusCode == 200) {
				response.writeHead(200, { 'Content-Type': 'text/plain' })
				var str = `Hello World,I'm view_counter${view_counter++}`
				//控制台输出,注意view_counter的值
				console.log(str + '\n-----------------------\n')
				//页面输出
				response.write(str)
			}
			response.end()
		}
	}
}
